import {Meta} from '@storybook/blocks';

<Meta title="Docs/Style options" />

# Style options

## CSS modules

Template uses vanilla CSS with `autoprefixer` enabled. To avoid classname collisions and reduce nesting we are using `css-modules`. To make css-modules work, stylesheet file name should have `.module` suffix.

```jsx
import React from 'react';
import classes from './Component.module.css';

const Component = () => <div className={classes.wrapper}>Component</div>;
```

## Add SASS/SCSS

SASS/SCSS support comes "out of the box" in CRA. To enable it:

1. Install `node-sass`

```shell
yarn add node-sass  --dev
```

2. Change `.lintstagedrc` to lint `scss` files instead of `css`.

```json
{
  "*.js": ["eslint --fix"],
  "*.scss": ["stylelint --fix"]
}
```

3. Change `rollup.config.js` to support `scss` files:

```js
postcss({
  extract: process.env.REACT_APP_PKG_STYLE || pkg.style,
  inline: false,
  plugins: postcssPlugins,
  extensions: ['scss'], // <=== here
});
```

4. Import `scss` files straight into Component.

```jsx
import React from 'react';
import classes from './Component.module.scss'; // note the changed extension

const Component = () => <div className={classes.wrapper}>Component</div>;
```

You can see all changes required to enable SASS/SCSS in [corresponding PR](https://github.com/morewings/cra-template-npm-library/pull/11).

## Add PostCSS

`PostCSS` support can be added using **file watcher**.

1. Install `postcss-cli` and related packages:

```shell script
yarn add --dev postcss-nested postcss-cli postcss-preset-env npm-run-all
```

2. Modify package scripts to add file watcher:

```json
{
  "build:style": "postcss src/**/*.pcss --dir src --base src --ext css",
  "watch:style": "yarn build:style -w",
  "start": "npm-run-all -p watch:style start:js",
  "start:js": "react-scripts start",
  "build:js": "react-scripts build",
  "build": "npm-run-all build:style build:js"
}
```

3. Add `postcss.config.js` file in the root folder. With following configuration:

```js
const pkg = require('./package.json');

module.exports = {
  plugins: [
    require('postcss-nested'), // handle nested selectors, like LESS or SASS
    require('postcss-preset-env')({
      browsers: pkg.browserslist.production, // use browsers list from production mode
      stage: 1,
    }),
  ],
};
```

4. Add rule to `.gitignore` and `.stylelintrc` to ignore all css files, since we are generating them.

`.gitignore`

```gitignore
# css
*.css
```

`.stylelintrc`

```json
{
  "ignoreFiles": ["**/*.snap", "**/*.css"]
}
```

5. Change `.lintstagedrc` to lint `pcss` files instead of `css`.

```json
{
  "*.js": ["eslint --fix"],
  "*.pcss": ["stylelint --fix"]
}
```

You can see all changes required to enable PostCSS in [corresponding PR](https://github.com/morewings/cra-template-npm-library/pull/12).
